/**
 * Created by jiangjunxian on 2016/12/15.
 */
$("i.fa-spinner").hide();
function updateOpts(r) {
	_opts.available = r.available;
	_opts.assigned = r.assigned;
	search('available');
	search('assigned');
}

$(".btn-assign").click(function() {
	var self = $(this);
	var target = self.data('target');
	var items = $('#' + target).val();
	if (items && items.length) {
		self.children("i.fa-spinner").fadeIn();
		$.post(self.attr('href'), {items: items}, function (r) {
			if(r.success > 0) updateOpts(r);
		}).always(function () {
			self.children("i.fa-spinner").fadeOut();
		});
	}
	return false;
});

$('.search').keyup(function () {
	search($(this).data('target'));
});

function search(target) {
	var $list = $('#'+target);
	$list.html('');

	var q = $('.search[data-target="'+target+'"]').val();
	var groups = {
		role: [$('<optgroup label="角色">'), false],
		permission: [$('<optgroup label="权限">'), false],
		route: [$('<optgroup label="路由">'), false]
	};

	$.each(_opts[target], function (name, group) {
		if(name.indexOf(q) >= 0) {
			$('<option>').text(name).val(name).appendTo(groups[group][0]);
			groups[group][1] = true;
		}
	});
	$.each(groups, function () {
		if(this[1]) {
			$list.append(this[0]);
		}
	})
}

search('available');
search('assigned');